package Jobs

import (
	"ali-hr/Services/Department"
	"ali-hr/Util"
	"errors"
	"github.com/gookit/goutil/dump"
	"strconv"
	"time"
)

/**
 * Created by Goland
 * User: wkk alisleepy@hotmail.com
 * Time: 2022/4/17 - 09:41
 * Desc: <Excel相关操作>
 */

func ExportDepartment(params map[string]interface{}) (string, string, error) {
	// 1、获取部门数据
	departments, count := Department.List(0, 0, params, true)
	dump.P("导出部门，部门个数为：", count)
	if count == 0 {
		return "", "", errors.New("数据为空")
	}

	// 2、处理部门数据,处理为[]map格式，便于excel导出
	var data []map[string]string
	for _, department := range departments {
		var temp = make(map[string]string)
		temp["id"] = strconv.Itoa(int(department.Id))
		temp["level"] = department.Level
		temp["name"] = department.Name
		if department.Parent == nil {
			temp["parent_name"] = "-"
		} else {
			temp["parent_name"] = department.Parent.Name
		}
		temp["name_path"] = department.NamePath
		if department.Leader == nil {
			temp["leader"] = "-"
		} else {
			temp["leader"] = department.Leader.Name
		}
		if department.Company == nil {
			temp["company"] = "-"
		} else {
			temp["company"] = department.Company.Name
		}
		temp["status"] = department.Status
		temp["created_at"] = (department.CreatedAt).String() // time.Time 转 string
		data = append(data, temp)
	}

	// format不能为map，map是无序的，会导致每次获取的key顺序不一致
	//format := map[string]string{
	//	"id":          "编号",
	//	"level":       "部门等级",
	//	"name":        "部门名称",
	//	"parent_name": "父级部门",
	//	"name_path":   "部门路径",
	//	"leader":      "部门负责人",
	//	"company":     "法人主体",
	//	"status":      "部门状态",
	//	"created_at":  "创建时间",
	//}

	// 3、写入Excel，返回存储路径
	var fieldName, fieldDesc []string
	fieldName = append(fieldName, "id", "level", "name", "name_path", "parent_name", "leader", "company", "status", "created_at")
	fieldDesc = append(fieldDesc, "编号", "部门等级", "部门名称", "部门路径", "父级部门", "部门负责人", "法人主体", "部门状态", "创建时间")
	// 4、设置样式
	style := make(map[string]map[string]string)
	// 4-1：设置宽度
	style["width"] = map[string]string{
		"C": "25",
		"D": "40",
		"E": "25",
		"G": "30",
		"I": "30",
	}

	var excel Util.Excel
	fileName := "部门数据_" + strconv.Itoa(int(time.Now().Unix())) + ".xlsx"
	filePath, err := excel.Write2Excel(data, fileName, fieldName, fieldDesc, style)
	if err != nil {
		return "", "", err
	}
	return fileName, filePath, err
}
